﻿using AutoMapper;
using DocumentFormat.OpenXml.Spreadsheet;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

using MyMES.Domain.W.Liststructure;
using MyMES.Domain.zmc;
using MyMES.Domain.zyy;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Read.API.Application.Commends.Productionorderss;
using MyMES.Read.API.Dtos;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Org.BouncyCastle.Asn1.Ocsp;

namespace MyMES.Read.API.Controllers.ZMC.Productionorderss
{
    [Route("api/[controller]/[Action]")]
    [ApiController]
    public class ProductionorderssController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly IBaseRepository<woekderProess> workderRepository;

        private readonly IBaseRepository<Process> prosRepository;
        private readonly IBaseRepository<Productionorders> productionorderRepository;

        private readonly IBaseRepository<Materialmanagement> materiasRepository;
        private readonly IBaseRepository<WorkOrder> workordersRepository;
        private readonly IMapper mapper;

        public ProductionorderssController(IMediator mediator, IBaseRepository<woekderProess> workderRepository, IBaseRepository<Process> prosRepository, IBaseRepository<Productionorders> productionorderRepository, IBaseRepository<Materialmanagement> materiasRepository, IBaseRepository<WorkOrder> workordersRepository, IMapper mapper)
        {
            this.mediator = mediator;
            this.workderRepository = workderRepository;
            this.prosRepository = prosRepository;
            this.productionorderRepository = productionorderRepository;
            this.materiasRepository = materiasRepository;
            this.workordersRepository = workordersRepository;
            this.mapper = mapper;
        }







        /// <summary>
        /// 获取生产信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpGet]
        public async Task<APIPaging<List<WorkOrder>>> GetProductionorderss([FromQuery]GetProductionorderssWorkCommends request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 显示物品信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// 
        [HttpGet]
        public async Task<APIPaging<List<Materialmanagement>>> GetProductionorderssMater([FromQuery]GetProductionorderssMaterCommends request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 获取工序流程
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpGet]
        public async Task<APIPaging<List<ProcessinfoDto>>>GetProductionorderssProcess([FromQuery]GetProductionorderssProcessCommends request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 获取生产订单明细
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<APIResult<List<ProductiondetailsDtos>>> GetProductiondetails([FromQuery]GetProductiondetailsCommends request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 获取工序流程--中间表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpGet]
        public async Task<APIPaging<List<woekderProessProduprocDtos>>> GetwoekderProess([FromQuery]GetwoekderProessCommends request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }


        /// <summary>
        /// 获取生产物品数据---生产详情
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpGet]
        public async Task<APIResult<List<MaterialmanagementProductionDtos>>> GetMaterialmanagementProduction([FromQuery]GetMaterialmanagementProductionCommends request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 获取 工序流程--详情
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpGet]
        public async Task<APIResult<List<WorkpromaterDtos>>> GetWorkProcessMater([FromQuery]GetWorkProcessMaterCommends request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 获取 报工记录--详情
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpGet]
        public async Task<APIResult<List<WorkpromaterDtos>>> GetWorkProcessMaterByWorkId([FromQuery]GetWorkProcessMaterByWorkIdCommends request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 获取操作记录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpGet]
        public async Task<APIResult<List<woekderProess>>> GetWorkoperate([FromQuery]GetWorkoperateCommends request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 导出生产工单信息
        /// </summary>
        /// <returns></returns>

        [HttpGet]
        public async Task<IActionResult> ExelProduction()
        {
            try
            {
                var sql = @"SELECT a.*,b.Materialnumber,b.Materialname,b.Specification,b.Unit,b.InboundNumber,c.WorkOrderCoding,c.WorkOrderName,d.ProductionordersNo,d.ProductionordersName ,d.Head,d.Department ,d.ProductionordersStatus,d.PlanStartTime,d.PlanEndTime FROM woekderproess a LEFT JOIN materialmanagement b on a.MId=b.MId  LEFT JOIN workorder c on a.WorkOrderId=c.WorkOrderId  LEFT JOIN productionorders d on a.ProductionordersId=d.ProductionordersId    where a.IsDelete=false ORDER BY a.woekderProessId DESC";


                var workder = await workderRepository.SelectAsync(sql);
                var productions = await productionorderRepository.SelectAsync(sql);
                var materias = await materiasRepository.SelectAsync(sql);
                var workorders = await workordersRepository.SelectAsync(sql);


                var Rlist = mapper.Map<List<ProducStoresWorkOrdeDto>>(workder);
                var produc = mapper.Map<List<ProducStoresWorkOrdeDto>>(productions);
                var rarriva = mapper.Map<List<ProducStoresWorkOrdeDto>>(materias);
                var workorderss = mapper.Map<List<ProducStoresWorkOrdeDto>>(workorders);



                //循环赋值
                foreach (var item in Rlist)
                {
                    item.ProductionordersNo = produc.Where(x => x.ProductionordersId == item.ProductionordersId).FirstOrDefault()?.ProductionordersNo;
                    item.ProductionordersName = produc.Where(x => x.ProductionordersId == item.ProductionordersId).FirstOrDefault()?.ProductionordersName;
                    item.Head = produc.Where(x => x.ProductionordersId == item.ProductionordersId).FirstOrDefault()?.Head;
                    item.Department = produc.Where(x => x.ProductionordersId == item.ProductionordersId).FirstOrDefault()?.Department;
                    item.ProductionordersStatus = produc.Where(x => x.ProductionordersId == item.ProductionordersId).FirstOrDefault().ProductionordersStatus;
                    item.yield = produc.Where(x => x.ProductionordersId == item.ProductionordersId).FirstOrDefault()?.yield;
                    item.PlanStartTime = produc.Where(x => x.ProductionordersId == item.ProductionordersId).FirstOrDefault().PlanStartTime;
                    item.PlanEndTime = produc.Where(x => x.ProductionordersId == item.ProductionordersId).FirstOrDefault().PlanEndTime;

                    item.Materialnumber = rarriva.Where(x => x.MId == item.MId).FirstOrDefault()?.Materialnumber;
                    item.Materialname = rarriva.Where(x => x.MId == item.MId).FirstOrDefault()?.Materialname;
                    item.Specification = rarriva.Where(x => x.MId == item.MId).FirstOrDefault()?.Specification;
                    item.Unit = rarriva.Where(x => x.MId == item.MId).FirstOrDefault().Unit;


                    item.WorkOrderCoding = workorderss.Where(x => x.WorkOrderId == item.WorkOrderId).FirstOrDefault()?.WorkOrderCoding;
                    item.WorkOrderName = workorderss.Where(x => x.WorkOrderId == item.WorkOrderId).FirstOrDefault()?.WorkOrderName;
                }

                // 创建Excel工作簿
                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("生产工单信息");

                // 创建标题行
                IRow headerRow = sheet.CreateRow(0);
                headerRow.CreateCell(0).SetCellValue("生产工单编号");
                headerRow.CreateCell(1).SetCellValue("生产工单名称");
                headerRow.CreateCell(2).SetCellValue("状态");
                headerRow.CreateCell(3).SetCellValue("负责人");
                headerRow.CreateCell(4).SetCellValue("所在部门");
                headerRow.CreateCell(5).SetCellValue("物料编号");
                headerRow.CreateCell(6).SetCellValue("出库数量");
                headerRow.CreateCell(7).SetCellValue("生产单号");
                headerRow.CreateCell(8).SetCellValue("规格");
                headerRow.CreateCell(9).SetCellValue("合格数量");
                headerRow.CreateCell(10).SetCellValue("不合格数量");
                headerRow.CreateCell(11).SetCellValue("计划开始时间");
                headerRow.CreateCell(12).SetCellValue("计划结束时间");
                headerRow.CreateCell(13).SetCellValue("删除标志位");

                // 填充数据行
                int rowIndex = 1;
                foreach (var item in Rlist)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex++);

                
                    dataRow.CreateCell(0).SetCellValue(item.ProductionordersNo);
                    dataRow.CreateCell(1).SetCellValue(item.ProductionordersName);
                    dataRow.CreateCell(2).SetCellValue(item.ProductionordersStatus ?"已下单":"未下单");
                    dataRow.CreateCell(3).SetCellValue(item.Head);
                    dataRow.CreateCell(4).SetCellValue(item.Department);
                    dataRow.CreateCell(5).SetCellValue(item.Materialnumber);
                    dataRow.CreateCell(6).SetCellValue(item.InboundNumber);
                    dataRow.CreateCell(7).SetCellValue(item.WorkOrderCoding); 
                    dataRow.CreateCell(8).SetCellValue(item.Specification); 
                    dataRow.CreateCell(9).SetCellValue(item.Goodproduct); 
                    dataRow.CreateCell(10).SetCellValue(item.Notproduct); 
                    dataRow.CreateCell(11).SetCellValue(item.PlanStartTime.ToString("yyyy-MM-dd "));
                    dataRow.CreateCell(12).SetCellValue(item.PlanEndTime.ToString("yyyy-MM-dd "));
                   dataRow.CreateCell(13).SetCellValue(item.IsDelete ? "是" : "否");
                }

                // 生成Excel文件流
                byte[] buffer;
                using (var ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    buffer = ms.ToArray();
                }

                // 设置MIME类型并返回文件
                var mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                return File(buffer, mimeType, "生产工单信息.xlsx");
            }
            catch (Exception ex)
            {

                // 处理异常，记录日志等
                return StatusCode(500, "内部服务器错误: " + ex.Message);
            }
        }


        /// <summary>
        /// 导出工序流程--详情
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet]
        public async Task<IActionResult> ExelprocessList()
        {
            try
            {
                string sql = $"select a.*,b.ProcessNo,b.ProcessName,b.Processdescris ,c.PlanStartTime,c.PlanEndTime,c.yield ,c.Head,c.Department FROM woekderproess a LEFT JOIN process b on a.ProcessID=b.ProcessID  LEFT JOIN  Productionorders c on a.ProductionordersId=c.ProductionordersId  ";


                var workpro = workderRepository.SelectAsync(sql).Result;
                var produc = productionorderRepository.SelectAsync(sql).Result;
                var proc = prosRepository.SelectAsync(sql).Result;

                var workpros = mapper.Map<List<WorkpromaterDtos>>(workpro);
                var producs = mapper.Map<List<WorkpromaterDtos>>(produc);
                var procs = mapper.Map<List<WorkpromaterDtos>>(proc);


                foreach (var item in workpros)
                {
                    item.ProcessNo = procs.Where(x => x.ProcessID == item.ProcessID).FirstOrDefault().ProcessNo;
                    item.ProcessName = procs.Where(x => x.ProcessID == item.ProcessID).FirstOrDefault().ProcessName;
                    item.Processdescris = procs.Where(x => x.ProcessID == item.ProcessID).FirstOrDefault().Processdescris;
                    item.PlanStartTime = produc.Where(x => x.ProductionordersId == item.ProductionordersId).FirstOrDefault().PlanStartTime;
                    item.PlanEndTime = produc.Where(x => x.ProductionordersId == item.ProductionordersId).FirstOrDefault().PlanEndTime;
                    item.yield = produc.Where(x => x.ProductionordersId == item.ProductionordersId).FirstOrDefault().yield;
                    item.Head = produc.Where(x => x.ProductionordersId == item.ProductionordersId).FirstOrDefault().Head;
                    item.Department = produc.Where(x => x.ProductionordersId == item.ProductionordersId).FirstOrDefault().Department;


                }
                // 创建Excel工作簿
                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("生产工序信息");

                // 创建标题行
                IRow headerRow = sheet.CreateRow(0);
                headerRow.CreateCell(0).SetCellValue("工序编号");
                headerRow.CreateCell(1).SetCellValue("工序名称");
                headerRow.CreateCell(2).SetCellValue("负责人");
                headerRow.CreateCell(3).SetCellValue("所在部门");
                headerRow.CreateCell(4).SetCellValue("计划开始时间");
                headerRow.CreateCell(5).SetCellValue("计划结束时间");
                headerRow.CreateCell(6).SetCellValue("计划产量");
            

                // 填充数据行
                int rowIndex = 1;
                foreach (var item in workpros)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex++);


                    dataRow.CreateCell(0).SetCellValue(item.ProcessNo);
                    dataRow.CreateCell(1).SetCellValue(item.ProcessName);
                    dataRow.CreateCell(2).SetCellValue(item.Head);
                    dataRow.CreateCell(3).SetCellValue(item.Department);
                    dataRow.CreateCell(4).SetCellValue(item.PlanStartTime.ToString("yyyy-MM-dd "));
                    dataRow.CreateCell(5).SetCellValue(item.PlanEndTime.ToString("yyyy-MM-dd "));
                    dataRow.CreateCell(6).SetCellValue(item.yield);
               
                }

                // 生成Excel文件流
                byte[] buffer;
                using (var ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    buffer = ms.ToArray();
                }

                // 设置MIME类型并返回文件
                var mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                return File(buffer, mimeType, "生产工序信息.xlsx");
            }
            catch (Exception ex)
            {


                // 处理异常，记录日志等
                return StatusCode(500, "内部服务器错误: " + ex.Message);
            }
        }




        /// <summary>
        /// 导出报工数据--详情
        /// </summary>
        /// <returns></returns>

        [HttpGet]
        public async Task<IActionResult> ExelSigning()
        {
            try
            {
                string sql = $"select a.*,b.ProcessNo,b.ProcessName,b.Processdescris ,c.PlanStartTime,c.PlanEndTime,c.yield ,c.Head,c.Department FROM woekderproess a LEFT JOIN process b on a.ProcessID=b.ProcessID  LEFT JOIN  Productionorders c on a.ProductionordersId=c.ProductionordersId  ";


                var workpro = workderRepository.SelectAsync(sql).Result;
                var produc = productionorderRepository.SelectAsync(sql).Result;
                var proc = prosRepository.SelectAsync(sql).Result;

                var workpros = mapper.Map<List<WorkpromaterDtos>>(workpro);
                var producs = mapper.Map<List<WorkpromaterDtos>>(produc);
                var procs = mapper.Map<List<WorkpromaterDtos>>(proc);


                foreach (var item in workpros)
                {
                    item.ProcessNo = procs.Where(x => x.ProcessID == item.ProcessID).FirstOrDefault().ProcessNo;
                    item.ProcessName = procs.Where(x => x.ProcessID == item.ProcessID).FirstOrDefault().ProcessName;
                    item.Processdescris = procs.Where(x => x.ProcessID == item.ProcessID).FirstOrDefault().Processdescris;
                    item.PlanStartTime = produc.Where(x => x.ProductionordersId == item.ProductionordersId).FirstOrDefault().PlanStartTime;
                    item.PlanEndTime = produc.Where(x => x.ProductionordersId == item.ProductionordersId).FirstOrDefault().PlanEndTime;
                    item.yield = produc.Where(x => x.ProductionordersId == item.ProductionordersId).FirstOrDefault().yield;
                    item.Head = produc.Where(x => x.ProductionordersId == item.ProductionordersId).FirstOrDefault().Head;
                    item.Department = produc.Where(x => x.ProductionordersId == item.ProductionordersId).FirstOrDefault().Department;


                }

                //     using (IWorkbook workbook = new XSSFWorkbook())
                // 创建Excel工作簿
                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("报工数据");

                // 创建标题行
                IRow headerRow = sheet.CreateRow(0);
                headerRow.CreateCell(0).SetCellValue("工序编号");
                headerRow.CreateCell(1).SetCellValue("工序名称");
                headerRow.CreateCell(2).SetCellValue("负责人");
                headerRow.CreateCell(3).SetCellValue("所在部门");
                headerRow.CreateCell(4).SetCellValue("计划开始时间");
                headerRow.CreateCell(5).SetCellValue("计划结束时间");
                headerRow.CreateCell(6).SetCellValue("计划产量");
                headerRow.CreateCell(7).SetCellValue("合格数");
                headerRow.CreateCell(8).SetCellValue("不合格数");
                headerRow.CreateCell(9).SetCellValue("状态");



                // 填充数据行
                int rowIndex = 1;
                foreach (var item in workpros)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex++);


                    dataRow.CreateCell(0).SetCellValue(item.ProcessNo);
                    dataRow.CreateCell(1).SetCellValue(item.ProcessName);
                    dataRow.CreateCell(2).SetCellValue(item.Head);
                    dataRow.CreateCell(3).SetCellValue(item.Department);
                    dataRow.CreateCell(4).SetCellValue(item.PlanStartTime.ToString("yyyy-MM-dd "));
                    dataRow.CreateCell(5).SetCellValue(item.PlanEndTime.ToString("yyyy-MM-dd "));
                    dataRow.CreateCell(6).SetCellValue(item.yield);
                    dataRow.CreateCell(7).SetCellValue(item.Goodproduct);
                    dataRow.CreateCell(8).SetCellValue(item.Notproduct);
                    dataRow.CreateCell(9).SetCellValue(item.Zt ? "已质检" : "未质检");

                }

                // 生成Excel文件流
                byte[] buffer;
                using (var ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    buffer = ms.ToArray();
                }

                // 设置MIME类型并返回文件
                var mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                return File(buffer, mimeType, "报工数据.xlsx");
            }
            catch (Exception ex)
            {


                // 处理异常，记录日志等
                return StatusCode(500, "内部服务器错误: " + ex.Message);
            }
        }




        /// <summary>
        /// 操作记录--导出
        /// </summary>
        /// <returns></returns>

        [HttpGet]
        public IActionResult Execlworkopen()
        {
            try
            {
                string sql = $"select * from woekderproess";


                var workpro = workderRepository.SelectAsync(sql).Result;
             


                // 创建Excel工作簿
                IWorkbook workbook = new XSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("操作记录");

                // 创建标题行
                IRow headerRow = sheet.CreateRow(0);
                headerRow.CreateCell(0).SetCellValue("操作人");
                headerRow.CreateCell(1).SetCellValue("操作时间");




                // 填充数据行
                int rowIndex = 1;
                foreach (var item in workpro)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex++);


                    dataRow.CreateCell(0).SetCellValue(item.Fzr);
                    dataRow.CreateCell(1).SetCellValue(item.CreateTime.ToString("yyyy-MM-dd "));
            

                }

                // 生成Excel文件流
                byte[] buffer;
                using (var ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    buffer = ms.ToArray();
                }

                // 设置MIME类型并返回文件
                var mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                return File(buffer, mimeType, "操作记录.xlsx");
            }
            catch (Exception ex)
            {

                // 处理异常，记录日志等
                return StatusCode(500, "内部服务器错误: " + ex.Message);
            }

        }

    }
}
